<script setup>
import { ref, computed, watch, onMounted } from 'vue'
import { PlusIcon, XMarkIcon, MagnifyingGlassIcon } from '@heroicons/vue/20/solid'
import axios from 'axios'
import { useToast } from '@/Composables/useToast'
import Modal from '@/Components/UI/Modal.vue'
import PrimaryButton from '@/Components/Base/PrimaryButton.vue'
import SecondaryButton from '@/Components/Base/SecondaryButton.vue'
import BaseTextInput from '@/Components/Base/BaseTextInput.vue'
import BaseTextArea from '@/Components/Base/BaseTextArea.vue'

const props = defineProps({
    modelValue: {
        type: [Number, String, null],
        default: null
    },
    disabled: {
        type: Boolean,
        default: false
    }
})

const emit = defineEmits(['update:modelValue'])

const toast = useToast()
const seriesList = ref([])
const loading = ref(false)
const search = ref('')
const showCreateModal = ref(false)
const creating = ref(false)

// 创建新系列的表单数据
const newSeries = ref({
    name: '',
    description: '',
    featured_image: ''
})

// 选中的系列
const selectedSeries = computed(() => {
    if (!props.modelValue) return null
    return seriesList.value.find(s => s.id === props.modelValue)
})

// 过滤后的系列列表
const filteredSeries = computed(() => {
    if (!search.value) return seriesList.value
    const keyword = search.value.toLowerCase()
    return seriesList.value.filter(s => 
        s.name.toLowerCase().includes(keyword) ||
        (s.description && s.description.toLowerCase().includes(keyword))
    )
})

// 加载系列列表
const loadSeries = async () => {
    loading.value = true
    try {
        const response = await axios.get(route('api.series.index'))
        seriesList.value = response.data
    } catch (error) {
        console.error('加载系列列表失败:', error)
        toast.error('加载系列列表失败')
    } finally {
        loading.value = false
    }
}

// 创建新系列
const createSeries = async () => {
    if (!newSeries.value.name.trim()) {
        toast.error('请输入系列名称')
        return
    }

    creating.value = true
    try {
        const response = await axios.post(route('api.series.store'), newSeries.value)
        const createdSeries = response.data.series
        
        // 添加到列表
        seriesList.value.push(createdSeries)
        
        // 选中新创建的系列
        emit('update:modelValue', createdSeries.id)
        
        // 重置表单
        newSeries.value = {
            name: '',
            description: '',
            featured_image: ''
        }
        
        showCreateModal.value = false
        toast.success('系列创建成功')
    } catch (error) {
        console.error('创建系列失败:', error)
        toast.error(error.response?.data?.message || '创建系列失败')
    } finally {
        creating.value = false
    }
}

// 选择系列
const selectSeries = (seriesId) => {
    emit('update:modelValue', seriesId)
}

// 清除选择
const clearSelection = () => {
    emit('update:modelValue', null)
}

// 监听 modelValue 变化，如果选中的系列不在列表中，加载它
watch(() => props.modelValue, async (newValue) => {
    if (newValue && !selectedSeries.value) {
        try {
            const response = await axios.get(route('api.series.show', newValue))
            const series = response.data
            if (!seriesList.value.find(s => s.id === series.id)) {
                seriesList.value.push(series)
            }
        } catch (error) {
            console.error('加载系列详情失败:', error)
        }
    }
}, { immediate: true })

onMounted(() => {
    loadSeries()
})
</script>

<template>
    <div class="space-y-2">
        <!-- 当前选中的系列 -->
        <div v-if="selectedSeries" class="flex items-center justify-between p-3 bg-orange-50 dark:bg-orange-900/20 border border-orange-200 dark:border-orange-800 rounded-lg">
            <div class="flex items-center space-x-3">
                <div class="flex-1">
                    <div class="font-medium text-gray-900 dark:text-white">
                        {{ selectedSeries.name }}
                    </div>
                    <div v-if="selectedSeries.description" class="text-sm text-gray-600 dark:text-gray-400 mt-1">
                        {{ selectedSeries.description }}
                    </div>
                    <div class="text-xs text-gray-500 dark:text-gray-500 mt-1">
                        {{ selectedSeries.post_count || 0 }} 篇文章
                    </div>
                </div>
            </div>
            <button
                v-if="!disabled"
                @click="clearSelection"
                type="button"
                class="ml-2 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300"
            >
                <XMarkIcon class="h-5 w-5" />
            </button>
        </div>

        <!-- 系列选择器 -->
        <div v-else class="space-y-2">
            <!-- 搜索框 -->
            <div class="relative">
                <MagnifyingGlassIcon class="absolute left-3 top-1/2 transform -translate-y-1/2 h-5 w-5 text-gray-400" />
                <input
                    v-model="search"
                    type="text"
                    :disabled="disabled"
                    placeholder="搜索系列..."
                    class="block w-full pl-10 pr-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md shadow-sm focus:ring-orange-500 focus:border-orange-500 dark:bg-gray-700 dark:text-white sm:text-sm"
                />
            </div>

            <!-- 系列列表 -->
            <div v-if="!loading" class="max-h-60 overflow-y-auto border border-gray-200 dark:border-gray-700 rounded-md">
                <div
                    v-for="series in filteredSeries"
                    :key="series.id"
                    @click="!disabled && selectSeries(series.id)"
                    :class="[
                        'p-3 cursor-pointer hover:bg-gray-50 dark:hover:bg-gray-800 transition-colors',
                        disabled && 'cursor-not-allowed opacity-50'
                    ]"
                >
                    <div class="font-medium text-gray-900 dark:text-white">
                        {{ series.name }}
                    </div>
                    <div v-if="series.description" class="text-sm text-gray-600 dark:text-gray-400 mt-1 line-clamp-2">
                        {{ series.description }}
                    </div>
                    <div class="text-xs text-gray-500 dark:text-gray-500 mt-1">
                        {{ series.post_count || 0 }} 篇文章
                    </div>
                </div>
                <div
                    v-if="filteredSeries.length === 0"
                    class="p-3 text-sm text-gray-500 dark:text-gray-400 text-center"
                >
                    没有找到系列
                </div>
            </div>

            <!-- 加载状态 -->
            <div v-else class="p-3 text-center text-gray-500 dark:text-gray-400">
                加载中...
            </div>

            <!-- 创建新系列按钮 -->
            <button
                v-if="!disabled"
                @click="showCreateModal = true"
                type="button"
                class="w-full flex items-center justify-center px-4 py-2 border border-dashed border-gray-300 dark:border-gray-600 rounded-md text-sm font-medium text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-800 transition-colors"
            >
                <PlusIcon class="h-5 w-5 mr-2" />
                创建新系列
            </button>
        </div>

        <!-- 创建系列弹窗 -->
        <Modal :show="showCreateModal" @close="showCreateModal = false">
            <div class="p-6">
                <h2 class="text-lg font-medium text-gray-900 dark:text-white mb-4">
                    创建新系列
                </h2>

                <div class="space-y-4">
                    <div>
                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                            系列名称 <span class="text-red-500">*</span>
                        </label>
                        <BaseTextInput
                            v-model="newSeries.name"
                            type="text"
                            placeholder="请输入系列名称"
                            class="w-full"
                        />
                    </div>

                    <div>
                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                            系列描述
                        </label>
                        <BaseTextArea
                            v-model="newSeries.description"
                            placeholder="请输入系列描述（可选）"
                            rows="3"
                            class="w-full"
                        />
                    </div>

                    <div>
                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                            封面图片 URL
                        </label>
                        <BaseTextInput
                            v-model="newSeries.featured_image"
                            type="text"
                            placeholder="请输入封面图片 URL（可选）"
                            class="w-full"
                        />
                    </div>
                </div>

                <div class="mt-6 flex justify-end space-x-3">
                    <SecondaryButton @click="showCreateModal = false">
                        取消
                    </SecondaryButton>
                    <PrimaryButton @click="createSeries" :disabled="creating">
                        {{ creating ? '创建中...' : '创建' }}
                    </PrimaryButton>
                </div>
            </div>
        </Modal>
    </div>
</template>

